package concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Created by chenxin34 on 2018/5/28 下午2:12.
 */
public class ConditionTest {
    public static void main(String[] args) throws InterruptedException {
        Lock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        IntegerHolder x = new IntegerHolder(1);

        new Thread(() -> {
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            System.out.println("A do");
            x.setA(3);
            try {
                reentrantLock.lock();
                boolean c = condition.await(5, TimeUnit.SECONDS);
                System.out.println(c);
//                condition.await();
                System.out.println(Thread.currentThread().getName() + " A do 2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B do");
            System.out.println(x.getA());
            try {
                reentrantLock.lock();
                condition.signal();
            } finally {
                reentrantLock.unlock();
            }
        }).start();

        Thread.sleep(5000);
        System.out.println(((ReentrantLock) reentrantLock).getHoldCount());
        System.out.println(Thread.currentThread().getName() + " done");
    }

    private static class IntegerHolder {
        private Integer a;

        public IntegerHolder(Integer a) {
            this.a = a;
        }

        public Integer getA() {
            return a;
        }

        public void setA(Integer a) {
            this.a = a;
        }
    }
}
